package com.lbb.springboot.util;

import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

//通过“addFormDataPart”可以添加多个上传的文件。
public class OkHttpCallBackWrap {
    public  static  void main(String[] args) throws IOException {
        String url="http://192.168.0.126/ulbb/uploadimage";
        post(url);
    }
    public static void post(String url) throws IOException {
        File file = new File("D:\\xcx\\img\\201811\\201811\\1.png");
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("application/octet-stream", "1.mp4", fileBody)
                .addFormDataPart("fileName","fileName")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        final okhttp3.OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
        OkHttpClient okHttpClient = httpBuilder
                //设置超时
                .connectTimeout(100, TimeUnit.SECONDS)
                .writeTimeout(150, TimeUnit.SECONDS)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }

            @Override
            public void onFailure(Call arg0, IOException e) {
                // TODO Auto-generated method stub
                System.out.println(e.toString());

            }

        });
    }
}